package org.example.struct.array;

/**
 * @author liyishan
 * @date 2023/8/25 10:27
 * @apiNote
 */

public class M04Search {


    public static void main(String[] args) {
        int[] nums = new int[]{1, 2, 3, 4, 5, 5, 7, 8, 9,};
        int count = test(nums,5);
        System.out.println(count);
    }

    public static int test1(int[] nums,int target){
        int n = nums.length;
        int count = 0 ;
        for(int i = 0;i<n;i++){
            if(nums[i] == target){
                count ++;
            }
        }
        return count;
    }


    public static int test(int[] nums, int target) {
        int leftIdx =binarySearch(nums,target,true);
        int rightIdx = binarySearch(nums,target,false)-1;
        if(leftIdx <=rightIdx && rightIdx < nums.length && nums[leftIdx] == target){
            return rightIdx-leftIdx+1;
        }
        return 0;
    }

    public static int binarySearch(int[] nums,int target,boolean lower){
        int left = 0, right = nums.length - 1,ans =nums.length;
        while(left <= right){
            int mid = (left+right)/2;
            if(nums[mid] > target || (lower && nums[mid] >= target)){
                right = mid - 1;
                ans = mid;
            }else{
                left = mid + 1;
            }
        }
        return ans;
    }
}
